import SHA from 'jssha';

const mainApiSignatureKey    = 'srs_signature_yoren2016';
const pltApiSignatureKey     = 'c0e9dcfdf2bf16fa5f169d744f142eac1d70dee1';
const modulesApiSignatureKey = 'yO7rE1nE0ck2Ey';

const NONCE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateNonce() {
    let nonce = '';
    for (let i = 0; i < 6; i++) {
        let randomIndex = Math.floor(Math.random() * NONCE_ALPHABET.length);
        let letter = NONCE_ALPHABET[randomIndex];
        nonce += letter;
    }
    return nonce;
}

function generateSignature(apiSecretKey) {
    const nonce = generateNonce();
    const timestamp = (new Date()).getTime();

    const sha = new SHA('SHA-1', 'TEXT');
    sha.update(`${apiSecretKey}${nonce}${timestamp}`);
    const signature = sha.getHash('HEX');

    return { nonce, timestamp, signature };
}

export default {
    generateMainApiSignature() {
        return generateSignature(mainApiSignatureKey);
    },
    generatePltApiSignature() {
        return generateSignature(pltApiSignatureKey);
    },
    generateModulesApiSignature() {
        return generateSignature(modulesApiSignatureKey);
    }
};